package utils.xml.com;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class WriteXMLFile {

    public static void main(String argv[]) {
    }

    public void CreateXml() {
        try {

            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

            final Document doc = docBuilder.newDocument();

            Element rootElement = doc.createElement("Books");
            doc.appendChild(rootElement);

            //Create Category 1>>>>>>>>>>>>>>>>>>>>>>
            Element categoryElement1 = doc.createElement("Category");
            Attr attCatType = doc.createAttribute("type");
            attCatType.setValue("1");
            categoryElement1.setAttributeNode(attCatType);
            rootElement.appendChild(categoryElement1);
            //Fin Book<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

            //Create Category 2>>>>>>>>>>>>>>>>>>>>>>
            Element categoryElement2 = doc.createElement("Category");
            Attr attCatType2 = doc.createAttribute("type");
            attCatType2.setValue("2");
            categoryElement2.setAttributeNode(attCatType2);
            rootElement.appendChild(categoryElement2);
            //Fin Book<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

            //Create of Book Example>>>>>>>>>>>>>>>>>>>>>>
            Element book1 = doc.createElement("Book");
            Attr attribute1 = doc.createAttribute("name");
            attribute1.setValue("The World on day");
            book1.setAttributeNode(attribute1);

            Node category1 = doc.createElement("Summary");
            category1.setTextContent("The details from book here.");
            book1.appendChild(category1);
            //Fin Book<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


            //Create of Book Example>>>>>>>>>>>>>>>>>>>>>>
            Element book2 = doc.createElement("Book");
            Attr attribute2 = doc.createAttribute("name");
            attribute2.setValue("National Geographic");
            book2.setAttributeNode(attribute2);

            Node category2 = doc.createElement("Summary");
            category2.setTextContent("TV channel tv cable.");
            book2.appendChild(category2);
            //Fin Book<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

            categoryElement1.appendChild(book1);
            categoryElement2.appendChild(book2);


            OutputFormat format = new OutputFormat(doc);
            format.setIndenting(true);
            format.setIndent(4);

            Writer out = new StringWriter();

            XMLSerializer serializer = new XMLSerializer(out, format);
            serializer.serialize(doc);

            FileOutputStream fwriter = new FileOutputStream(new File("CollectionBooks.xml"));
            fwriter.write(out.toString().getBytes());
            fwriter.flush();
            fwriter.close();

            System.out.print("File Created!!!");

        } catch (ParserConfigurationException pce) {
            Logger.getLogger(WriteXMLFile.class.getName()).log(Level.SEVERE, null, pce);
        } catch (IOException e) {
            Logger.getLogger(WriteXMLFile.class.getName()).log(Level.SEVERE, null, e);
        }
    }

    public List<String> GetBooks() {
        List<String> data = new ArrayList<String>();
        try {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

            Document doc = docBuilder.parse(new File("CollectionBooks.xml"));
            doc.getDocumentElement().normalize();

            XPath xPath = XPathFactory.newInstance().newXPath();
            NodeList nodeDepend = (NodeList) xPath.evaluate("//Book", doc, XPathConstants.NODESET);
            System.out.println("#####nodeListSize" + nodeDepend.getLength());

            for (int i = 0; i < nodeDepend.getLength(); i++) {
                Element element = (Element) nodeDepend.item(i);
                System.out.println("#####" + element.getTagName() + "   " + element.getAttribute("name"));
                data.add(element.getAttribute("name"));
            }

        } catch (ParserConfigurationException ex) {
            Logger.getLogger(WriteXMLFile.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(WriteXMLFile.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(WriteXMLFile.class.getName()).log(Level.SEVERE, null, ex);
        } catch (XPathExpressionException ex) {
            Logger.getLogger(WriteXMLFile.class.getName()).log(Level.SEVERE, null, ex);
        }
        return data;
    }

    public List<String> FindBookByCategory(int category) {
        List<String> data = new ArrayList<String>();
        try {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

            Document doc = docBuilder.parse(new File("CollectionBooks.xml"));
            doc.getDocumentElement().normalize();

            XPath xPath = XPathFactory.newInstance().newXPath();
            NodeList nodeDepend = (NodeList) xPath.evaluate("/Books/Category[@type='" + category + "']", doc, XPathConstants.NODESET);
            //NodeList nodeDepend = (NodeList) xPath.evaluate("//Book/Category[text()='" + category + "']", doc, XPathConstants.NODESET);
            System.out.println("#####nodeListSize" + nodeDepend.getLength());

            if (nodeDepend.getLength() >= 1) {
                NodeList child = nodeDepend.item(0).getChildNodes();
                for (int i = 0; i < child.getLength() - 1; i++) {
                    Node node = child.item(i);
                    Element element = (Element) child.item(i);
                    if (node.getNodeType() == Node.ELEMENT_NODE) {
                        System.out.println("#####" + node.getNodeName());
                        data.add(node.getNodeName());
                    }
                }
            }

        } catch (ParserConfigurationException ex) {
            Logger.getLogger(WriteXMLFile.class
                    .getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(WriteXMLFile.class
                    .getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(WriteXMLFile.class
                    .getName()).log(Level.SEVERE, null, ex);
        } catch (XPathExpressionException ex) {
            Logger.getLogger(WriteXMLFile.class
                    .getName()).log(Level.SEVERE, null, ex);
        }
        return data;
    }
}
